<?php

namespace addons\sum\controller;

use addons\sum\controller\Common;
use app\admin\model\sum\Signin as SigninModel;
use app\admin\model\sum\UserGift as UserGiftModel;
use think\Db;

class Signin extends Common
{

    protected $noNeedLogin = ['rule'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $this->error(__('No Results were found'));
    }

    public function rule()
    {
        $user = auth_user();
        $weekDays = [];
        for ($i = 0; $i < 7; $i++) {
            $weekDays[] = date('Y-m-d', strtotime("monday this week +$i days"));
        }
        $signin_rule=sum_config('shop.basic.signin_gift');
        $i=0;
        foreach ($signin_rule as &$v){
            $v['is_signin']=0;
            $v['image']=$v['image']?cdnurl($v['image'],true):$v['image'];
            if($user){
                $date=$weekDays[$i];
                $signin=SigninModel::where('user_id',$user['id'])->where('date',$date)->find();
                if($signin){
                    $v['is_signin']=1;
                }
            }
            $i++;
        }
        $this->success(__('Success'),$signin_rule);
    }

    /**
     * 签到
     * @return void
     */
    public function create()
    {
        $user = auth_user();
        $signin_rule=sum_config('shop.basic.signin_gift');
        $dayShortName = strtolower(date('D'));
        $today_date=date('Y-m-d');
        $today_rule=$signin_rule[$dayShortName];
        $signin=SigninModel::where('user_id',$user['id'])->where('date',$today_date)->find();
        if($signin){
            $this->error(__('今日已签到'));
        }
        // 添加签到记录
        $signin_m=new SigninModel();
        $signin_m->user_id=$user['id'];
        $signin_m->gift_id=$today_rule['id'];
        $signin_m->date=$today_date;
        $signin_m->save();
        // 增加用户礼物道具
        $user_gift=UserGiftModel::where('user_id',$user['id'])->where('gift_id',$today_rule['id'])->find();
        if($user_gift){
            $user_gift->num=$user_gift->num+1;
            $user_gift->save();
        }else{
            $user_gift= new UserGiftModel();
            $user_gift->user_id=$user['id'];
            $user_gift->gift_id=$today_rule['id'];
            $user_gift->num=1;
            $user_gift->save();
        }
        $this->success(__('Success'));
    }



}
